import 'package:azlistview/azlistview.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:changxindianzishangwu/dao/title_dao.dart';
import 'package:changxindianzishangwu/else/lib/common/index.dart';
import 'package:changxindianzishangwu/model/address_book_model.dart';
import 'package:changxindianzishangwu/pages/contacts/contacts_titiles_page.dart';
import 'package:changxindianzishangwu/pages/contacts/create_titls_page.dart';
import 'package:changxindianzishangwu/pages/contacts/search_user_page.dart';
import 'package:changxindianzishangwu/pages/my/settings/send_message_all_page.dart';
import 'package:changxindianzishangwu/provider/friend.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/fade_router.dart';
import 'package:changxindianzishangwu/util/widget_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:tencent_im_sdk_plugin/enum/V2TimFriendshipListener.dart';
import 'package:tencent_im_sdk_plugin/manager/v2_tim_manager.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_callback.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_application.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_application_result.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_info_result.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_user_full_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_value_callback.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';

import 'checkbox_widget.dart';

class GetMessageWidget extends StatefulWidget {
  int type;
  String groupId;
  String groupName;
  List<String> userList;
  GetMessageWidget(
      {Key key, this.type = 1, this.groupId, this.groupName, this.userList})
      : super(key: key);

  @override
  _GetMessageWidgetState createState() => _GetMessageWidgetState();
}

class _GetMessageWidgetState extends State<GetMessageWidget> {
  String packageName = "ContactsPage:";
  int count = 0;
  V2TIMManager timManager = TencentImSDKPlugin.v2TIMManager;
  List userIDList;
  List<String> userId;
  List<AddressBookModel> addressBookList = [];
  List<AddressBookModel> addressBookListCopy = [];
  Future<V2TimValueCallback<List<V2TimFriendInfoResult>>> userEntity;
  List<V2TimFriendInfoResult> friendInfoResult;
  List<V2TimFriendInfo> f;
  V2TimUserFullInfo _userEntity;
  List<V2TimFriendApplication> applicationList;
  V2TimValueCallback<V2TimFriendApplicationResult> data;
  List<AddressBookModel> someUser = [];
  List<String> someUserid = [];

  @override
  void initState() {
    super.initState();

    SchedulerBinding.instance.addPostFrameCallback((_) {
      loadUser();
      _getFriendsAddList();
    });

    //showToast(widget.userList.toString());
  }

  _getFriendsAddList() async {
    print("comming!!_getFriendsAddList");
    data = await TencentImSDKPlugin.v2TIMManager
        .getFriendshipManager()
        .getFriendApplicationList();
    setState(() {
      count = data.data.unreadCount;
    });
  }

  initImFriendLister() {
    timManager.v2TIMFriendshipManager.setFriendListener(listener:
        V2TimFriendshipListener(onFriendApplicationListAdded: (application) {
      setState(() {
        f = Provider.of<FriendListModel>(context, listen: true).friendList;
      });
    }));
  }

  loadUser() async {
    V2TimValueCallback<List<V2TimFriendInfo>> friendRes =
        await TencentImSDKPlugin.v2TIMManager
            .getFriendshipManager()
            .getFriendList();
    f = friendRes.data;
    Provider.of<FriendListModel>(context, listen: false).setFriendList(f);
    f.forEach((element) {
      print(element.userID);
    });
    addressBookList = [];
    addressBookListCopy = [];
    userId = [];
    for (var i = 0; i < f.length; i++) {
      addressBookListCopy.add(AddressBookModel(
          name: f[i].friendRemark == null || f[i].friendRemark == ""
              ? f[i].userProfile.nickName == null ||
                      f[i].userProfile.nickName == ""
                  ? "未设置昵称"
                  : f[i].userProfile.nickName
              : f[i].friendRemark,
          headerUrl: f[i].userProfile.faceUrl ?? "",
          userId: f[i].userID,
          self: f[i].userProfile.selfSignature));
      userId.add(f[i].userID);

      print(userId);
    }

    userEntity =
        timManager.v2TIMFriendshipManager.getFriendsInfo(userIDList: userId);
    userEntity.then((value) {
      if (value != null) {
        friendInfoResult = value.data;
        if (friendInfoResult != null && friendInfoResult.length > 0) {
          friendInfoResult.forEach((element) {
            _userEntity = element.friendInfo.userProfile;
            print("这里是数据：：：：${_userEntity.toJson()}");
          });
          addressBookList.addAll(addressBookListCopy);
          SuspensionUtil.setShowSuspensionStatus(addressBookList);
          _handleList(addressBookList);
        }
      }
    });
    setState(() {});
  }

  void _handleList(List<AddressBookModel> list) {
    if (list.isEmpty) return;
    for (int i = 0, length = list.length; i < length; i++) {
      String pinyin =
          PinyinHelper.getPinyinE(list[i].name == "" ? "没有姓名" : list[i].name);
      String tag = pinyin.substring(0, 1).toUpperCase();
      list[i].namePinyin = pinyin;

      print(list[i]);
      print(list[i].name);
      print(list[i].namePinyin);

      if (RegExp('[A-Z]').hasMatch(tag)) {
        list[i].tagIndex = tag;
      } else {
        list[i].tagIndex = '#';
      }
    }
    SuspensionUtil.sortListBySuspensionTag(list);

    SuspensionUtil.setShowSuspensionStatus(list);

    setState(() {});
  }

  setFriendApplicationRead() async {
    V2TimCallback res = await TencentImSDKPlugin.v2TIMManager
        .getFriendshipManager()
        .setFriendApplicationRead();
    print(res.toJson());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        elevation: 0,
        title: Text(
          "联系人 ",
          style:
              TextStyle(fontSize: ScreenUtil().setSp(22), color: Colors.black),
        ),
        actions: [
          InkWell(
            onTap: () async {
              if (widget.type == 8) {
                Get.to(SendMessageAllPage(someUser: someUser)).then((value) {
                  Get.back(result: 'true');
                });
              } else {
                widget.userList.forEach((element) {
                  someUserid.add(element);
                });

                await TitleDao.updateTitle(
                    widget.groupId, someUserid.toSet().toList());

                Navigator.pushAndRemoveUntil(
                    context,
                    FadeRoute(CreateTitlsPage(
                      type: 2,
                      groupId: widget.groupId,
                      groupName: widget.groupName,
                    )),
                    (route) => false);
              }
            },
            child: Container(
              alignment: Alignment.center,
              margin: EdgeInsets.only(top: 11, bottom: 11, right: 15),
              height: 10,
              width: ScreenUtil().setWidth(60),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(6),
                color: Color.fromRGBO(0, 220, 169, 1),
              ),
              child: Text(
                "完成",
                style: TextStyle(
                    color: Colors.white, fontSize: ScreenUtil().setSp(14)),
              ),
            ),
          )
        ],
      ),
      body: SafeArea(
        child: Container(
          color: Colors.white,
          child: Column(
            children: [
              InkWell(
                onTap: () {
                  //dev.log(packageName + "搜索聊天记录跳转");
                  Get.to(() => SearchUserPage());
                },
                child: Container(
                    height: ScreenUtil().setHeight(32),
                    alignment: Alignment.center,
                    padding: EdgeInsets.only(left: 20),
                    margin: EdgeInsets.only(
                        left: ScreenUtil().setWidth(10),
                        top: ScreenUtil().setHeight(10),
                        right: ScreenUtil().setWidth(15),
                        bottom: 40),
                    decoration: BoxDecoration(
                        color: Color.fromRGBO(241, 241, 241, 1),
                        borderRadius: BorderRadius.circular(6)),
                    child: Text(
                      "搜索联系人、聊天记录",
                      style: TextStyle(
                          fontSize: 15,
                          color: Color.fromRGBO(153, 153, 153, 1)),
                    )),
              ),
              widget.type == 8
                  ? InkWell(
                      onTap: () {
                        Get.to(ContactsTitilesPage(
                          type: 3,
                        ));
                      },
                      child: ListTile(
                        leading: Text(
                          '选择标签',
                          style: TextStyle(fontSize: sp(15)),
                        ),
                        trailing: Icon(Icons.chevron_right),
                      ),
                    )
                  : SizedBox(),
              Expanded(
                child: AzListView(
                  data: addressBookList,
                  itemCount: addressBookList.length,
                  itemBuilder: (BuildContext context, int index) {
                    AddressBookModel model = addressBookList[index];
                    print(model.name);
                    // _userEntity =
                    //     friendInfoResult[index].friendInfo.userProfile ?? "";

                    return Container(
                      alignment: Alignment.bottomCenter,
                      height: 60,
                      child: Column(
                        children: [
                          InkWell(
                            onTap: () {
                              print(
                                  "-----------------------------------------------");
                              setState(() {
                                model.isCheck = !model.isCheck;
                              });
                              if (model.isCheck) {
                                someUser.add(model);

                                someUserid.add(model.userId);
                              } else {
                                someUser.remove(model);
                                someUserid.remove(model.userId);
                              }
                            },
                            child: Container(
                              height: 56,
                              child: Slidable(
                                  actionPane:
                                      SlidableScrollActionPane(), //滑出选项的面板 动画
                                  actionExtentRatio: 0.25,
                                  closeOnScroll: true,
                                  secondaryActions: <Widget>[
                                    IconSlideAction(
                                        caption: '删除',
                                        color: Colors.red,
                                        icon: Icons.delete,
                                        closeOnTap: true,
                                        onTap: () async {}),
                                  ],
                                  child: Row(
                                    children: <Widget>[
                                      Container(
                                        margin: EdgeInsets.only(left: 8),
                                        child: DefCheckBoxWidget(
                                            value: model.isCheck,
                                            onTap: (d) {
                                              //showToast(item.textElem.text);
                                              if (d) {
                                                someUser.add(model);

                                                someUserid.add(model.userId);
                                              } else {
                                                someUser.remove(model);
                                                someUserid.remove(model.userId);
                                              }

                                              setState(() {
                                                model.isCheck = d;
                                              });
                                              someUser.forEach((element) {
                                                print(
                                                    "someMessage++++++=========" +
                                                        element.name);
                                              });

                                              // showToast(
                                              //item.isCheckBox.toString());
                                            }),
                                      ),
                                      Container(
                                          margin: EdgeInsets.only(left: 8),
                                          height: width(40),
                                          width: width(40),
                                          decoration: BoxDecoration(
                                              borderRadius:
                                                  BorderRadius.circular(6),
                                              color: Colors.greenAccent,
                                              image: model.headerUrl == null
                                                  ? null
                                                  : DecorationImage(
                                                      image:
                                                          CachedNetworkImageProvider(
                                                              model
                                                                  .headerUrl))),
                                          child: ClipRRect(
                                            borderRadius:
                                                BorderRadius.circular(6),
                                            child: CachedNetworkImage(
                                              imageUrl: model.headerUrl,
                                              fit: BoxFit.cover,
                                            ),
                                          )),
                                      Container(
                                          margin: EdgeInsets.only(
                                            left: 15,
                                          ),
                                          child: Text(model.name ?? "",
                                              style:
                                                  TextStyle(fontSize: sp(15)))),
                                    ],
                                  )),
                            ),
                          ),
                          Divider(
                            height: 1,
                            indent: width(65),
                            endIndent: width(15),
                          )
                        ],
                      ),
                    );
                    ;
                  },
                  padding: EdgeInsets.zero,
                  susItemBuilder: (BuildContext context, int index) {
                    AddressBookModel model = addressBookList[index];
                    String tag = model.getSuspensionTag();
                    return WidGetUtils.getSusItem(context, tag);
                  },
                  indexBarData: ['★', ...kIndexBarData],
                  indexBarWidth: 15,
                  indexBarMargin: EdgeInsets.only(bottom: 4),
                  indexBarHeight: 460,
                  indexBarItemHeight: 13,
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
